package com.javaweb.dao.impl;

import com.javaweb.dao.CommentDao;
import com.javaweb.model.Comment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.util.Assert;

import java.sql.Date;
import java.util.List;
@Repository
public class CommentDaoImpl implements CommentDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

//    添加评论
    @Override
    public int insert(Comment comment) {
        String sql = "INSERT INTO" +
                " tb_comment (content, article_id,user_Id, " +
                "support, oppose,create_time,update_time) VALUES (?, ?,?,?,?,?,?)" ;
        Object [] args = new Object[]{
                comment.getContent(),
                comment.getArticleId(),
                comment.getUserId(),
                comment.getSupport(),
                comment.getOppose(),
                // java util Date   ->   java sql Date
                new Date(comment.getCreateTime().getTime()),
                new Date(comment.getUpdateTime().getTime())
        } ;
        return jdbcTemplate.update(sql, args);
    }

//    添加点赞
    @Override
    public int insertSupport(Integer commentId) {

        Assert.notNull(commentId);

        String sql = "update tb_comment" +
                " set support = support + 1  where  id = ?" ;

        return jdbcTemplate.update(sql, commentId);
    }

//    添加点差
    @Override
    public int insertOppose(Integer commentId) {
        Assert.notNull(commentId);

        String sql = "update tb_comment" +
                " set oppose = oppose + 1  where  id = ?" ;

        return jdbcTemplate.update(sql, commentId);
    }

//    查询文章的所有评论
    @Override
    public List<Comment> selectAllCommentsById(Integer articleId) {

       Assert.notNull(articleId);

        String sql = "SELECT id, content, article_id, user_id, support, oppose, create_time, update_time " +
                "FROM tb_comment WHERE article_id = ? ";

        return jdbcTemplate.query(sql, new Object[]{articleId},
                (rs, rowNum) -> {
            Comment comment = new Comment();
            comment.setId(rs.getInt("id"));
            comment.setContent(rs.getString("content"));
            comment.setArticleId(rs.getInt("article_id"));
            comment.setUserId(rs.getInt("user_id"));
            comment.setSupport(rs.getInt("support"));
            comment.setOppose(rs.getInt("oppose"));
            comment.setCreateTime(rs.getTimestamp("create_time"));
            comment.setUpdateTime(rs.getTimestamp("update_time"));
            return comment;
        });
    }

    }

